package cn.gson.springboot.model.service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.gson.springboot.model.dao.DestroyDao;
import cn.gson.springboot.model.dao.DestryDetailDao;
import cn.gson.springboot.model.dao.DrugDao;
import cn.gson.springboot.model.dao.DrugstorageCheckDao;
import cn.gson.springboot.model.dao.DrugstoragecheckDetailDao;
import cn.gson.springboot.model.dao.IndentDao;
import cn.gson.springboot.model.dao.IndentDetailDao;
import cn.gson.springboot.model.dao.InventoryDao;
import cn.gson.springboot.model.dao.InventoryDetailDao;
import cn.gson.springboot.model.dao.OutBoundDao;
import cn.gson.springboot.model.dao.OutboundDetailDao;
import cn.gson.springboot.model.dao.PutInStorageDao;
import cn.gson.springboot.model.dao.PutInStorageDetailDao;
import cn.gson.springboot.model.dao.ReturnGoodDao;
import cn.gson.springboot.model.dao.ReturnGoodsDetailDao;
import cn.gson.springboot.model.mapper.IndentMapper;
import cn.gson.springboot.model.pojos.Destroy;
import cn.gson.springboot.model.pojos.DestryDetail;
import cn.gson.springboot.model.pojos.Drug;
import cn.gson.springboot.model.pojos.DrugstorageCheck;
import cn.gson.springboot.model.pojos.DrugstoragecheckDetail;
import cn.gson.springboot.model.pojos.Indent;
import cn.gson.springboot.model.pojos.IndentDetail;
import cn.gson.springboot.model.pojos.Inventory;
import cn.gson.springboot.model.pojos.InventoryDetail;
import cn.gson.springboot.model.pojos.OutBound;
import cn.gson.springboot.model.pojos.OutboundDetail;
import cn.gson.springboot.model.pojos.PutInStorage;
import cn.gson.springboot.model.pojos.PutInStorageDetail;
import cn.gson.springboot.model.pojos.ReturnGood;
import cn.gson.springboot.model.pojos.ReturnGoodsDetail;
import cn.gson.springboot.model.vo.AuditVo;
import cn.gson.springboot.model.vo.DestructionVo;
import cn.gson.springboot.model.vo.IndentVo;
import cn.gson.springboot.model.vo.OutboundAo;
import cn.gson.springboot.model.vo.ReturndrugVo;
import cn.gson.springboot.model.vo.DrugscheckVo;

@Service
@Transactional(rollbackFor = Exception.class)
public class IndentService {
	
		@Autowired
		public IndentMapper indentmapper; //采购订单表mapper
		
		@Autowired
		private IndentDao indentdao; //采购订单表dao
		
		@Autowired
		private IndentDetailDao indentdetaildao; //采购订单详情表dao
		
		@Autowired
		private PutInStorageDao putindao; //入库表dao
		
		@Autowired
		private PutInStorageDetailDao putdetaildao; //入库详情表dao
		
		@Autowired
		private OutBoundDao outdao; //入库表dao
		
		@Autowired
		private OutboundDetailDao outdetaildao; //入库详情表dao
		
		@Autowired
		private ReturnGoodDao gooddao; //退药表dao
		
		@Autowired
		private ReturnGoodsDetailDao gooddeyaildao; //退药详情表dao
		
		@Autowired
		private DestroyDao destroydao; //销毁表dao
		
		@Autowired
		private DestryDetailDao destrydetaildao; //销毁详情表dao
		
		@Autowired
		private DrugDao drugdao;//药品表
		
		@Autowired
		private InventoryDao Inventorydao; //库存表dao
		
		@Autowired
		private InventoryDetailDao Indetaildao; //库存详情表dao
		
		@Autowired
		private DrugstorageCheckDao Drugcdao; //盘点表dao
		
		@Autowired
		private DrugstoragecheckDetailDao drugcdetaildao; //盘点详情表dao
		
		//查询采购订单
		public JSONArray FindAllIndent(Integer indentid,String oday,String tday) {
			return indentmapper.FindAllIndent(indentid, oday, tday) ;			
		}
		
		//查询采购订单详情
		public JSONArray findallindentdetails(Integer indentid) {
			return indentmapper.findallindentdetails(indentid) ;			
		}
		
		//查询待验收采购订单
		public JSONArray FindOtherIndent() {
			return indentmapper.FindOtherIndent();			
		}
		
		//查询待出库单
		public JSONArray Findapply() {
			return indentmapper.Findapply();			
		}
		
		//查询出库详情
		public JSONArray Findapplydet(Integer drugapplyid) {
			return indentmapper.Findapplydet(drugapplyid) ;			
		}
		
		//查询入库单
		public JSONArray FindAllPutInStorage(Integer inid,String aday,String bday) {
			return indentmapper.FindAllPutInStorage(inid, aday, bday);			
		}
		
		//查询采购订单详情
		public JSONArray FindByPutInStorage(Integer instorageid) {
			return indentmapper.FindByPutInStorage(instorageid) ;			
		}
		
		//生成采购订单
		public void saveOrder(IndentVo IndentVo) {
			//获取采购订单进行新增
			Indent indent = IndentVo.getIndent();
			
			Indent save = indentdao.save(indent);
			
			List<IndentDetail> details = IndentVo.getIndentDetail();
			//循环
			for (IndentDetail pur : details) {
				//添加订单信息
				pur.setIndent(indent);
				//查询药品
				Drug drug = drugdao.findById(pur.getDrug().getDrugNumber()).get();
				//重新赋值一下药品对象
				pur.setDrug(drug);
				
				indentdetaildao.save(pur);
			}
				
		}
		
		//生成入库订单
		public void savePut(AuditVo AuditVo) {
			//获取入库表进行新增
			PutInStorage putin = AuditVo.getPutin();
			
			PutInStorage save = putindao.save(putin);
			
			List<PutInStorageDetail> putdetails = AuditVo.getPutdetails();
			//循环
			for (PutInStorageDetail pur : putdetails) {
				//添加入库信息
				pur.setPutInStorage(putin);
				//查询库存药品
				Inventory inventory = Inventorydao.findById(pur.getInventory().getInventoryNumber()).get();
				//重新赋值一下库存对象
				pur.setInventory(inventory);
				
				putdetaildao.save(pur);
			}

			List<InventoryDetail> detail = AuditVo.getInventorydetails();
			//循环
			for (InventoryDetail pur : detail) {
				//添加库存信息
				Inventory inventory = Inventorydao.findById(pur.getInventory().getInventoryNumber()).get();
				pur.setInventory(inventory);
				Indetaildao.save(pur);
				//indentmapper.updateinven(pur.getInventory(), pur.getInventoryDetailsQuantity());
			}
				
		}
		
		//修改订单状态
		public JSONArray updateindent(Integer indentid) {
			return indentmapper.updateindent(indentid) ;			
		}

		//入库修改库存数量
		public JSONArray updateinven(Integer inventorynumber,Integer sum) {
			return indentmapper.updateinven(inventorynumber,sum) ;			
		}
		
		//查询出库单
		public JSONArray FindAlloutbound(Integer outboundnumber,String qday,String wday) {
			return indentmapper.FindAlloutbound(outboundnumber, qday, wday) ;			
		}
		
		//查询出库详情
		public JSONArray FindByOutbound(Integer outboundid) {
			return indentmapper.FindByOutbound(outboundid) ;			
		}
		
		//修改请领状态
		public JSONArray updateapply(Integer applyid) {
			return indentmapper.updateapply(applyid) ;			
		}
		
		//生成出库订单
		public void saveOutbound(OutboundAo OutboundAo) {
			//获取请领单进行新增
			OutBound out = OutboundAo.getOut();
			
			OutBound save = outdao.save(out);
			
			List<OutboundDetail> outbo = OutboundAo.getOutdetail();
			//循环
			for (OutboundDetail pur : outbo) {
				//添加订单信息
				pur.setOutBound(out);
				//查询药品
				Inventory inventory = Inventorydao.findById(pur.getInventory().getInventoryNumber()).get();
				//重新赋值一下药品对象
				pur.setInventory(inventory);
				
				
				//根据页面传过来的vo类-----得到药品单个发药数量
				Integer  drugeveryNumber = pur.getOutDetailsQuantity();
				Integer  drugeveryNumbers = pur.getOutDetailsQuantity();
				//根据详情找到库存id
				Integer drugNumber = pur.getInventory().getDrug().getDrugNumber();
				System.out.println("根据 详情找到药品id:"+drugNumber);
				//根据药品id找到所有药品批次
				JSONArray selectPici= indentmapper.FindAllpici(drugNumber);
				System.out.println("所有药品的批次:"+selectPici);
			    //根据药品id与药品批次找到药品库存数量
			    for (int i = 0; i <= selectPici.size(); i++) {
			    	OutboundDetail od=new OutboundDetail();
			    	//重新赋值一下药品对象
			    	od.setOutBound(out);
			    	od.setInventory(inventory);
			    	od.setOutDetailsQuantity(drugeveryNumbers);
			    	System.out.println("selectPici.size():"+selectPici.size());
			    	 //每个药品的批次
			    	Integer pici = selectPici.getJSONObject(i).getInteger("inventory_details_batch");
			    	System.out.println("每个药品的批次:"+pici);
			    	//得到每个药品对应批次的库存数量
			    	JSONArray drugAmount= indentmapper.FindAllpicisum(drugNumber,pici);
			    	System.out.println("每个药品对应批次的库存数量drugAmount:"+drugAmount);
			    	Integer everyAmount = drugAmount.getJSONObject(0).getInteger("inventory_details_quantity");
			    	System.out.println("每个药品对应批次everyAmount:"+everyAmount);
			    	
			    	//库存数量为零
			        if(everyAmount==0){
			        	System.out.println("everyAmount==0");
			        	continue;
			        }
			        
			    	//批次查出来此药品库存数量>=药品数量
			        if(drugeveryNumber<=everyAmount){
			        	System.out.println("批次查出来此药品库存数量>=药品数量");
			        	indentmapper.updatedinventpici(drugeveryNumber, drugNumber, pici);
			        	od.setOutDetailsShiji(drugeveryNumber);
			        	od.setOutDetailsPici(pici);
			        	outdetaildao.save(od);
			        	break;
			        }
			        
			        //批次查出来此药品库存数量<=药品数量
			        if(drugeveryNumber>everyAmount){
			        	 System.out.println("drugeveryNumber>everyAmount");
			        	 // 药品单个数量=药品单个数量-库存数量 
			        	 drugeveryNumber=drugeveryNumber-everyAmount;
			        	 indentmapper.updatedinventpici(everyAmount, drugNumber, pici);
			        	 od.setOutDetailsPici(pici);
			        	 od.setOutDetailsShiji(everyAmount);
			        	 outdetaildao.save(od);
			        	 continue;
			        }
			        
				}			
				
			}
				
		}
		
		//入库修改库存数量
		public JSONArray updatedinvent(Integer inventorynumber,Integer sum) {
			return indentmapper.updatedinvent(inventorynumber,sum) ;			
		}
		
		//入库修改库存数量
		public JSONArray updateaplaydis(Integer adetailsid,Integer sum) {
			return indentmapper.updateaplaydis(adetailsid,sum) ;			
		}
		
		//查询药品详细批次
		public JSONArray selectdrugs(Integer supplierno,Integer days,Integer dada,Integer dddd) {
			return indentmapper.selectdrugs(supplierno, days ,dada ,dddd);			
		}
		
		//生成退药订单
		public void saveReturn(ReturndrugVo ReturndrugVo) {
			//获取退药订单进行新增
			ReturnGood good = ReturndrugVo.getGood();
			
			ReturnGood save = gooddao.save(good);
			
			List<ReturnGoodsDetail> goods = ReturndrugVo.getGooddetail();
			//循环
			for (ReturnGoodsDetail pur : goods) {
				//添加订单信息
				pur.setReturnGood(good);
				//查询药品
				Inventory inventory = Inventorydao.findById(pur.getInventory().getInventoryNumber()).get();
				//重新赋值一下药品对象
				pur.setInventory(inventory);
				
				gooddeyaildao.save(pur);
			}
				
		}
		
		//退药修改库存数量
		public JSONArray updatekucun(Integer inventorynum,Integer sum) {
			return indentmapper.updatekucun(inventorynum,sum) ;			
		}
		
		//退药修改库存数量
		public JSONArray updateinpici(Integer inventorynum,Integer sum,Integer batch) {
			return indentmapper.updateinpici(inventorynum,sum,batch) ;			
		}
		
		//修改请领状态
		public JSONArray updatereturn(Integer returngoid,String checkpeople) {
			return indentmapper.updatereturn(returngoid,checkpeople) ;			
		}

		//生成销毁订单
		public void saveDestruction(DestructionVo DestructionVo) {
			//获取销毁订单进行新增
			Destroy destroy = DestructionVo.getDestroy();
			
			Destroy save = destroydao.save(destroy);
			
			List<DestryDetail> destroys = DestructionVo.getDestrydetail();
			//循环
			for (DestryDetail pur : destroys) {
				//添加订单信息
				pur.setDestroy(destroy);
				//查询药品
				Inventory inventory = Inventorydao.findById(pur.getInventory().getInventoryNumber()).get();
				//重新赋值一下药品对象
				pur.setInventory(inventory);
				
				destrydetaildao.save(pur);
			}
				
		}
		
		//销毁修改库存数量
		public JSONArray updateoutkucun(Integer inventorynum,Integer sum) {
			return indentmapper.updateoutkucun(inventorynum,sum) ;			
		}
		
		//销毁修改库存数量
		public JSONArray updateoutpici(Integer inventorynum,Integer sum,Integer batch) {
			return indentmapper.updateoutpici(inventorynum,sum,batch) ;			
		}
		
		//修改销毁状态
		public JSONArray updatedestroy(Integer destroyid,String checkpeople) {
			return indentmapper.updatedestroy(destroyid,checkpeople) ;			
		}
		
		//修改供应商
		public JSONArray updatedsuppliers(String phone,String people,Integer numb) {
			return indentmapper.updatedsuppliers(phone, people, numb);		
		}
		
		//盘点
		public void Drugscheck(Integer caty,String name) {
			
				DrugstorageCheck w=new DrugstorageCheck();
				
				w.setDrugchekPeople(name);
				w.setDrugchekTime(new Timestamp(new Date().getTime()));
				w.setDrugchekState(0);
				if(caty==1) {
					w.setDrugchekCategory("中药房");
				}else if(caty==2) {
					w.setDrugchekCategory("西药房");
				}
				Drugcdao.save(w);
				
				JSONArray druf= indentmapper.drugscheck(caty);
				
				Integer shijisum = 0;
				Integer shijisumc = 0;
				BigDecimal shijijine= new BigDecimal(0);
				BigDecimal shijijinec = new BigDecimal(0) ;
				
				for(Object obe : druf) {
					
					JSONObject obej= (JSONObject) obe;
					
					DrugstoragecheckDetail wd=new DrugstoragecheckDetail();
					
					wd.setDrugstorageCheck(w);
					
					//库存编号
					Inventory kucuns = new Inventory();
					JSONArray ku = indentmapper.invensum(obej.getInteger("num"));
					kucuns.setInventoryNumber(ku.getJSONObject(0).getInteger("numb"));
					wd.setInventory(kucuns);
					
					//库存数量
					JSONArray shu = indentmapper.invensum(obej.getInteger("num"));
					wd.setDrugchekdetailsBook(shu.getJSONObject(0).getInteger("sum"));
					
					//总数量
					shijisum +=shu.getJSONObject(0).getInteger("sum");
					
					//总金额					
					shijijine  =shijijine.add(new BigDecimal(shu.getJSONObject(0).getInteger("sum")*obej.getInteger("price")));
					
					//库存批次
					JSONArray pici = indentmapper.invensum(obej.getInteger("num"));					
					wd.setDrugchekdetailsPici(pici.getJSONObject(0).getInteger("pici"));					
					
					//入库总数量
					JSONArray insum = indentmapper.insum(obej.getInteger("psum"),obej.getInteger("pc"));										
					if(insum.getJSONObject(0)==null) {
						wd.setDrugruku(0);
					}else {
						wd.setDrugruku(insum.getJSONObject(0).getInteger("insum"));				
					}
					
					//出库总数量
					JSONArray outsum = indentmapper.outsum(obej.getInteger("psum"),obej.getInteger("pc"));
					if(outsum.getJSONObject(0)==null) {
						wd.setDrugchuku(0);;
					}else {
						wd.setDrugchuku(outsum.getJSONObject(0).getInteger("outsum"));				
					}
					
					//退药总数量
					JSONArray returnsum = indentmapper.returnsum(obej.getInteger("psum"),obej.getInteger("pc"));
					if(returnsum.getJSONObject(0)==null) {
						wd.setDrugtuiyao(0);
					}else {
						wd.setDrugtuiyao(returnsum.getJSONObject(0).getInteger("returnsum"));				
					}
					
					//销毁总数量
					JSONArray decisum = indentmapper.decisum(obej.getInteger("psum"),obej.getInteger("pc"));
					if(decisum.getJSONObject(0)==null) {
						wd.setDrugxiaohui(0);
					}else {
						wd.setDrugxiaohui(decisum.getJSONObject(0).getInteger("decisum"));				
					}
					
					drugcdetaildao.save(wd);
					
				}
				w.setDrugchekAllnumber(shijisum);
				w.setDrugchekAllmoney(shijijine);
				
			}
			
			//修改
			public String  update(String name ,String zhaiyao ,Timestamp times,Integer checkid,BigDecimal jinec,Integer sumc) {
				DrugstorageCheck drugstorageCheck = Drugcdao.findById(checkid).get();
				drugstorageCheck.setDrugcheckTwopeople(name);
				drugstorageCheck.setDrugchekZhaiyao(zhaiyao);
				drugstorageCheck.setDrugcheckEndtime(times);
				drugstorageCheck.setDrugchekState(1);
				drugstorageCheck.setDrugcheckDifferencemoney(jinec);
				drugstorageCheck.setDrugcheckState(sumc);
				DrugstorageCheck save = Drugcdao.save(drugstorageCheck);
				if(save!=null) {
					return "1";
				}else {
					return "2";
				}
			}
			
			//判断药品
			public boolean findByss(String name ,String stand ,Integer number,Integer type) {
				if(indentmapper.ifdrug(name, stand, number, type).isEmpty()==true) {
					return false;
				}
				return true;
			}
			
			//修改库存
			public JSONArray updatekusum(Integer shul, Integer invsum, Integer pici) {
				return indentmapper.updatekusum(shul, invsum, pici);		
			}
			
			//盘点实际数量
			public JSONArray updatetake(Integer shijisum, Integer slcha, Integer biaozhi, Integer tid) {
				return indentmapper.updatetake(shijisum, slcha, biaozhi,tid);		
			}
			
			//判断判断时间
			public boolean takes(String caty) {
				if(indentmapper.selecttake(caty).isEmpty()==true) {
					return false;
				}
				return true;
			}
			
		
}
